package cn.kingshion.juc;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 1. i++ 的原子性问题：
 * int i= 10;
 * i = i++;
 * 步骤： 读 ---> 改 ---> 写
 * int temp = i;
 * i = i+1;
 * i = temp;
 */
public class AtomicTest {
    public static void main(String[] args) {
        AtomicDemo atomic = new AtomicDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(atomic).start();
        }
    }
}

class AtomicDemo implements Runnable {
//    private volatile int serialNumber = 0;
    //使用 atomic 包下的类实现。
    private AtomicInteger serialNumber = new AtomicInteger(0);

    @Override
    public void run() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(getSerialNumber());
    }

    public int getSerialNumber() {
//        return serialNumber++;
        return serialNumber.getAndIncrement();
    }
}
